﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using YunLuPos.Entity;

namespace YunLuPos.Net.Http
{
   public class HttpBase
    {
        private log4net.ILog logger = log4net.LogManager.GetLogger(typeof(HttpBase));

        public static String ServerUrl = null;

        protected T doRequest<T>(Object data, String serviceName)
        {
            HttpWebResponse response = null;
            Encoding encoding = Encoding.UTF8;
            String content = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://"+ServerUrl+"/" + serviceName);
                Console.WriteLine("http://" + ServerUrl + "/" + serviceName);
                request.Timeout = NetConfig.Timeout;
                request.ReadWriteTimeout = NetConfig.ReadWriteTimeout;
                request.ContentType = "application/json;charset=utf8";
                request.Method = "POST";
                request.KeepAlive = true;
                request.ServicePoint.Expect100Continue = false;
                //是否使用 Nagle 不使用 提高效率 
                request.ServicePoint.UseNagleAlgorithm = false;
                //最大连接数 
                request.ServicePoint.ConnectionLimit = int.MaxValue;
                //数据是否缓冲 false 提高效率  
                request.AllowWriteStreamBuffering = false;

                String reqData = JsonConvert.SerializeObject(data);
                Console.WriteLine("=======请求参数=======");
                Console.WriteLine(serviceName);
                Console.WriteLine(reqData);
                Console.WriteLine("=======请求参数结束=======");
                byte[] buffer = encoding.GetBytes(reqData);
                request.ContentLength = buffer.Length;

                Stream ss = request.GetRequestStream();
                ss.Write(buffer, 0, buffer.Length);
                ss.Close();
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (UriFormatException e)
            {
                logger.Debug(e);
                throw NetException.NET_URL_ERROR;
            }
            catch (WebException we)
            {
                logger.Debug(we);
                response = (HttpWebResponse)we.Response;
            }
            //服务器连接失败
            if (response == null)
            {
                throw NetException.NET_UNKNOW_ERROR;
            }
            if (response.StatusCode == HttpStatusCode.OK)
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
                {
                    content = reader.ReadToEnd();
                   /* Console.WriteLine("返回值");
                    Console.WriteLine(content);*/
                    if (content == null || "".Equals(content))
                    {
                        throw NetException.SERVER_NO_BODY;
                    }
                    var jSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
                    ApiResult<T> result = JsonConvert.DeserializeObject<ApiResult<T>>(content,jSetting);
                    if ("success".Equals(result.code))
                    {
                        return result.data;
                    }else
                    {
                        throw new BizError(result.code, result.message);
                    }
                }
            }
            else
            {
                logger.Debug(response.StatusCode.ToString());
                if (HttpStatusCode.NotFound == response.StatusCode)
                {
                    throw NetException.SERVICE_NAME_ERROR;
                }
                throw NetException.SERVER_ERROR;
            }
        }

    }
}
